package com.action;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pojo.DepPOJO;
import com.service.DepService;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
@CrossOrigin("*")
public class DepAction {

    @Autowired
    private DepService depService;

    @Autowired
    private HttpServletRequest request;

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Value("${upload.dir}")
    private String images;

    @RequestMapping("/searchDep")
    public ResponseBean searchDep(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, Integer did, String dname) {
        IPage result = depService.searchDep(page, limit, did, dname);
        return new ResponseBean(0, result.getTotal(), result.getRecords());
    }


    @RequestMapping("/saveOrUpdateDep")
    public ResponseBean saveOrUpdateDep(DepPOJO dep) {
        boolean result = depService.saveOrUpdate(dep);//如果有主键且数据库存在就修改,否则新增
        if (result) {
            //复制到正式环境images
          /*  String images = request.getServletContext().getRealPath("/images");
            File file = new File(images);
            if (file.exists() == false) {
                file.mkdirs();
            }*/
            FileUtil.copy(tmp + dep.getImage(), images + dep.getImage(), true);
            return new ResponseBean(200, 0, "操作成功");
        }

        return new ResponseBean(500, 0, "操作失败");
    }

    @RequestMapping("/removeDep")
    public ResponseBean  removeDep(int id)
    {
        boolean f = depService.removeById(id);
        int code = f ? 200 : 500;
        return new ResponseBean(code,0,"");
    }


}
